<script lang="ts" setup>
  import {
    affiliatedYear,
    gender,
    rating,
    queryByParentCode,
  } from '@/api-new/dict';
  import { useForm } from '@/hooks/arco/useForm';
  import { useModeModalBinder } from '@/hooks/arco/useModeModalBinder';
  import { useSelectOption } from '@/hooks/arco/useSelectOption';
  import { onMounted, ref } from 'vue';
  import { createElder, deleteElder, updateElder } from '@/api-new/elderly';
  import { queryInstitutions } from '@/api-new/organizational-management';
  import useDetailDrawerBinder from '@/hooks/arco/useDetailDrawerBinder';

  const addressOptions = ref([]);

  const yearSelect = useSelectOption({
    name: '所属年度',
    apiFun: affiliatedYear,
    fieldNames: {
      label: 'name',
      value: 'id',
    },
  });

  const rateSelect = useSelectOption({
    name: '评级',
    apiFun: rating,
    fieldNames: {
      label: 'name',
      value: 'id',
    },
  });

  const genderSelect = useSelectOption({
    name: '性别',
    apiFun: gender,
    fieldNames: {
      label: 'name',
      value: 'id',
    },
  });

  const institutionsSelect = useSelectOption({
    name: '所属机构',
    apiFun: queryInstitutions,
    fieldNames: {
      label: 'instName',
      value: 'instId',
    },
  });

  const form = useForm({
    state: {
      elderId: '',
      name: '',
      gender: '',
      birthdate: '',
      idcardno: '',
      idcardType: undefined,
      ratingId: undefined,
      yearId: undefined,
      phone: '',
      provinceCode: '',
      cityCode: '',
      districtCode: '',
      streetCode: '',
      committeeCode: '',
      address: '',
      addressCode: [] as any[],
      provinceName: '',
      cityName: '',
      districtName: '',
      streetName: '',
      committeeName: '',
      instId: '',
      periodValidity: [] as string[],
      contacts: [
        {
          name: '',
          phoneNo: '',
        },
        {
          name: '',
          phoneNo: '',
        },
        {
          name: '',
          phoneNo: '',
        },
      ],
      validDate: '',
      startDate: '',
      contact1Name: '',
      contact1Phone: '',
    },
    rules: {
      name: {
        required: true,
        message: '请输入长者姓名',
      },
      phone: {
        required: true,
        message: '请输入长者手机号码',
      },
      gender: {
        required: true,
        message: '请选择长者性别',
      },
      birthdate: {
        required: true,
        message: '请选择长者生日',
      },
      idcardno: {
        required: true,
        message: '请输入长者身份证号',
      },
      ratingId: {
        required: true,
        message: '请选择护理级别',
      },
      yearId: {
        required: true,
        message: '请选择归属年份',
      },
      addressCode: {
        required: true,
        message: '请选择所在村镇',
      },
      address: {
        required: true,
        message: '请输入家庭地址',
      },
      instId: {
        required: true,
        message: '请选择所属机构',
      },
      periodValidity: {
        required: true,
        message: '请选择保障有效期',
      },
      contact1Name: {
        required: true,
        validator: (_: string, cb: any) => {
          const item = form.state.contacts[0];

          if (!item.name) {
            cb('请输入联系人姓名');
            return;
          }
          cb();
        },
      },
      contact1Phone: {
        required: true,
        validator: (_: string, cb: any) => {
          const item = form.state.contacts[0];

          if (!item.phoneNo) {
            cb('请输入联系人手机号');
            return;
          }
          cb();
        },
      },
    },
  });

  const fallback = () => {
    const { provinceName, cityName, districtName, streetName, committeeName } =
      form.state;
    return `${provinceName}-${cityName}-${districtName}-${streetName}-${committeeName}`;
  };

  const modal = useDetailDrawerBinder({
    modes: ['detail', 'add', 'edit'] as const,
    delete: true,
    deleteApi: () => deleteElder(form.state.elderId),
    deleteText: '确定删除当前长者吗？',
    onShow(mode, otherParams) {
      if (mode === 'add') {
        form.backToInit();
      } else {
        form.setFieldsValue(otherParams);
        form.state.ratingId = otherParams.ratingLevel;
        const {
          provinceCode,
          cityCode,
          districtCode,
          streetCode,
          committeeCode,
          validDate,
          startDate,
        } = otherParams;
        form.state.addressCode = [
          provinceCode,
          cityCode,
          districtCode,
          streetCode,
          committeeCode,
        ];
        form.state.periodValidity = [startDate, validDate];
        form.state.phone = otherParams.phoneNo;
      }
    },
    async onOkClick(mode) {
      await form.validate();

      const { periodValidity, addressCode, ...data } = form.state;

      // console.log('addressCode', addressCode);

      const [provinceCode, cityCode, districtCode, streetCode, committeeCode] =
        addressCode;

      const [startDate, validDate] = periodValidity;

      data.provinceCode = provinceCode;
      data.cityCode = cityCode;
      data.districtCode = districtCode;
      data.streetCode = streetCode;
      data.committeeCode = committeeCode;
      data.startDate = startDate;
      data.validDate = validDate;

      if (mode === 'add') {
        return createElder(data);
      }
      return updateElder(data);
    },
  });

  onMounted(() => {
    queryByParentCode().then((res) => {
      addressOptions.value = res;
    });
  });

  const fieldNames = { value: 'areaCode', label: 'areaName' };

  const loadMore = (option: any, done: any) => {
    queryByParentCode(option.areaCode).then((res) => {
      if (option.areaLevel === 4) {
        res.forEach((element: any) => {
          element.isLeaf = true;
        });
      }
      done(res);
    });
  };

  defineExpose(modal.expose);
</script>

<template>
  <detail-drawer width="500px" v-bind="modal.bindProps">
    <a-form
      :disabled="modal.modeIs('detail')"
      v-bind="form.bindProps"
      layout="vertical"
    >
      <!-- 长者信息 -->
      <a-card class="mb-4">
        <template #title>
          <div class="flex items-center">
            <icon-user class="mr-2" />
            <span>长者信息</span>
          </div>
        </template>
        <div class="grid grid-cols-1 gap-4">
          <a-form-item field="name" label="长者姓名" required>
            <a-input v-model="form.state.name" placeholder="请输入长者姓名" />
          </a-form-item>
          <a-form-item field="idcardno" label="身份证号" required>
            <a-input
              v-model="form.state.idcardno"
              placeholder="请输入身份证号"
            />
          </a-form-item>
          <a-form-item field="gender" label="性别" required>
            <a-select
              v-model="form.state.gender"
              v-bind="genderSelect.bindProps"
            />
          </a-form-item>
          <a-form-item field="birthdate" label="出生日期" required>
            <a-date-picker
              v-model="form.state.birthdate"
              placeholder="请选择出生日期"
              class="w-full"
            />
          </a-form-item>

          <a-form-item field="phone" label="手机号码" required>
            <a-input v-model="form.state.phone" placeholder="请输入手机号码" />
          </a-form-item>
        </div>
      </a-card>

      <!-- 评级信息 -->
      <a-card class="mb-4">
        <template #title>
          <div class="flex items-center">
            <icon-star class="mr-2" />
            <span>评级信息</span>
          </div>
        </template>
        <div class="grid grid-cols-1 gap-4">
          <a-form-item field="yearId" label="所属年度" required>
            <a-select
              v-model="form.state.yearId"
              v-bind="yearSelect.bindProps"
            />
          </a-form-item>
          <a-form-item field="ratingId" label="评级" required>
            <a-select
              v-model="form.state.ratingId"
              v-bind="rateSelect.bindProps"
            />
          </a-form-item>

          <a-form-item field="instId" label="归属机构" required>
            <a-select
              v-model="form.state.instId"
              v-bind="institutionsSelect.bindProps"
            />
          </a-form-item>

          <a-form-item field="periodValidity" label="保障有效期" required>
            <a-range-picker
              v-model="form.state.periodValidity"
              class="w-full"
              value-format="YYYY-MM-DD"
            />
          </a-form-item>
        </div>
      </a-card>

      <!-- 村镇信息 -->
      <a-card class="mb-4">
        <template #title>
          <div class="flex items-center">
            <icon-home class="mr-2" />
            <span>村镇信息</span>
          </div>
        </template>
        <div class="grid grid-cols-1 gap-4">
          <a-form-item field="addressCode" label="所属村镇">
            <a-cascader
              v-model="form.state.addressCode"
              :options="addressOptions"
              placeholder="请选择所属村镇"
              :field-names="fieldNames"
              :load-more="loadMore"
              :fallback="fallback"
              :path-mode="true"
              class="w-full"
            />
          </a-form-item>
          <a-form-item field="address" label="家庭地址" required>
            <a-input
              v-model="form.state.address"
              placeholder="请输入家庭地址"
            />
          </a-form-item>
        </div>
      </a-card>

      <!-- 紧急联系人信息 -->
      <a-card>
        <template #title>
          <div class="flex items-center">
            <icon-phone class="mr-2" />
            <span>紧急联系人信息</span>
          </div>
        </template>
        <div class="flex flex-col">
          <div
            v-for="(item, index) in form.state.contacts"
            :key="index"
            class="grid grid-cols-1 gap-4"
          >
            <a-form-item
              :field="`contact${index + 1}Name`"
              :label="`家属${index + 1}姓名`"
            >
              <a-input v-model="item.name" placeholder="请输入家属姓名" />
            </a-form-item>
            <a-form-item
              :field="`contact${index + 1}Phone`"
              :label="`家属${index + 1}手机号码`"
            >
              <a-input
                v-model="item.phoneNo"
                placeholder="请输入家属手机号码"
              />
            </a-form-item>
          </div>
        </div>
      </a-card>
    </a-form>
  </detail-drawer>
</template>

<style scoped>
  .mb-4 {
    margin-bottom: 1rem;
  }
</style>
